package com.fub.view.mapcomponents;

import java.util.List;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathDashPathEffect;

import com.fub.guidance.Graph;
import com.fub.guidance.Point;
import com.fub.guidance.Vertex;
import com.fub.util.PreferenceDAO;
import com.fub.util.Util;

public class RouteComponent {

	private Graph graph;
	private static final int DISTANCE_TO_BOTTOM = 5;
	private List<Vertex> shortestPath;
	private Paint paintPath;
	private String sourceId;
	private String destinationId;
	private PreferenceDAO preferenceDao;

	public RouteComponent(String sourceID, String destinationID,
			PreferenceDAO preferenceDAO) {
		this.sourceId = sourceID;
		this.destinationId = destinationID;
		this.preferenceDao = preferenceDAO;
		this.graph = Graph.getInstance();
		if (!this.graph.isWayCalculated(sourceID, destinationID)) {
			this.graph.calculateWay(sourceID, destinationID);
		}		
		this.shortestPath = this.graph.getShortestPath();
		initPaints();
	}

	public String getSourceId() {
		return this.sourceId;
	}

	public String getDestinationId() {
		return this.destinationId;
	}

	private void initPaints() {
		this.paintPath = new Paint(Paint.ANTI_ALIAS_FLAG);
		this.paintPath.setStyle(Paint.Style.STROKE);
		this.paintPath.setStrokeWidth(6);
		this.paintPath.setColor(Color.argb(200, 148, 23, 23));
		this.paintPath.setPathEffect(new PathDashPathEffect(makePathDash(), 12, 20,
				PathDashPathEffect.Style.ROTATE));
		this.paintPath.setShadowLayer(2, 5, 5, Color.argb(100, 0, 0, 0));
	}

	public void draw(Canvas canvas) {
		Path p = new Path();
		Vertex start = null;
		int startVertex = 0;
		for (Vertex vertex : this.shortestPath) {

			if (vertex.getPosition().getZ() == this.preferenceDao.getCurrentEtage()) {
				start = vertex;
				break;
			}
			startVertex++;
		}

		if (start == null)
			return;

		Point startPositionOnDisplay = Util.calculateZoomedPosition(
				start.getPosition(), this.preferenceDao);
		p.moveTo(startPositionOnDisplay.getX(), startPositionOnDisplay.getY());
		for (int i = startVertex + 1; i < this.shortestPath.size(); i++) {

			Vertex to = this.shortestPath.get(i);
			if (to.getPosition().getZ() == this.preferenceDao.getCurrentEtage()) {
				Point toPositionOnDisplay = Util.calculateZoomedPosition(
						to.getPosition(), this.preferenceDao);
				p.lineTo(toPositionOnDisplay.getX(), toPositionOnDisplay.getY()
						- DISTANCE_TO_BOTTOM);
			}
		}
		canvas.drawPath(p, this.paintPath);
	}

	private Path makePathDash() {
		Path p = new Path();
		p.moveTo(0, -3);
		p.lineTo(4, 0);
		p.lineTo(0, 3);
		p.lineTo(0, -3);
		return p;
	}
}
